package com.hepinghospital.user.ui.activity.userinfo;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.base.BaseApplication;
import com.hepinghospital.user.ui.dialog.ApplyPermissionDialog;
import com.hepinghospital.user.ui.dialog.SelectPicModeDialog;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.PermissionsChecker;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.constant.JDConstant;
import com.rest.observer.BaseObserver;
import com.rest.response.MyFamilyResponse;
import com.rest.response.PicUploadResponse;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.AES128;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.UriUtils;
import jz.joyoung.robot.util.UtilString;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * Created by HP on 2020/3/7.
 */
@Deprecated
public class ChangePhoneActivity extends BaseActivity {

    public static final int REQUEST_OPEN_CAMERA = 0x011;
    public static final int REQUEST_GALLERY = 0x022;

    @BindView(R.id.shenfenzheng1)
    ImageView shenfenzheng1;
    @BindView(R.id.shenfenzheng2)
    ImageView shenfenzheng2;
    @BindView(R.id.shenfenzheng3)
    ImageView shenfenzheng3;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_id_card)
    TextView tv_id_card;

    @BindView(R.id.tv_area)
    TextView tv_area;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.tv_pre_phone)
    TextView tv_pre_phone;
    @BindView(R.id.edt_phone)
    EditText edt_phone;
    ImageView currentImageView;
    String shenfenzheng1Id, shenfenzheng2Id, shenfenzheng3Id, endPhoneNo, resourceId;
    //原图像 URI
    public Uri imgUriOri;
    //原图像 路径
    public static String imgPathOri;

    public ProgressDialog dialog;

    public String patientId, id;

    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
    };
    private PermissionsChecker mPermissionsChecker; // 权限检测器

    @Override
    protected void initViews() {
        tv_pre_phone.setText(UtilString.hidePhone(endPhoneNo));
        mPermissionsChecker = new PermissionsChecker(mContext);
    }

    @Override
    protected void initData() {
        patientId = getIntent().getStringExtra("patientId");
        id = getIntent().getStringExtra("id");
        endPhoneNo = getIntent().getStringExtra("endPhoneNo");
        assert endPhoneNo != null;
        Log.e("手机号1111-----", endPhoneNo);
        getDetail();
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_change_phone;
    }

    @OnClick(R.id.shenfenzheng1)
    void shenfenzheng1() {
        currentImageView = shenfenzheng1;
        getPermission();
    }

    @OnClick(R.id.shenfenzheng2)
    void shenfenzheng2() {
        currentImageView = shenfenzheng2;
        getPermission();
    }

    @OnClick(R.id.shenfenzheng3)
    void shenfenzheng3() {
        currentImageView = shenfenzheng3;
        getPermission();
    }

    @OnClick(R.id.btn_save)
    void btn_save() {
        updatePhone();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        //data的返回值根据
        switch (requestCode) {
            case REQUEST_OPEN_CAMERA:
                getPresignedUrl(imgPathOri);
//                uploadFile( imgPathOri );
                break;
            case REQUEST_GALLERY:
                if (data != null) {
                    Uri imgUriSel = data.getData();
                    String imgPathSel = UriUtils.formatUri(this, imgUriSel);
                    getPresignedUrl(imgPathSel);
//                    uploadFile( imgPathSel );
                }
                break;

        }
    }


    /**
     * 获取minio服务器域名
     *
     * @time 2020/12/2 10:21
     */
    private void getPresignedUrl(String imgPathSel) {

        dialog = ProgressDialog.show(ChangePhoneActivity.this, "提示", "正在上传中…", true, false, null);

        // 1-病历 2-评论(反馈) 3-头像 4-轮播图 5-用户资源 6-图标 7-封面',
        RestProxy.getInstance().getPresignedUrl("1", new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(String baseStringResponse) {
                try {
                    String data = baseStringResponse;
                    if (data.contains("?")) {
                        String substring = data.substring(0, data.indexOf("?"));
                        resourceId = substring.substring(substring.lastIndexOf("/") + 1);
                        Log.e("presignedUrl -----", resourceId);
                        uploadFileMinio(imgPathSel,baseStringResponse);
                    }

                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(ChangePhoneActivity.this, e);
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 上传图片到minio服务器
     * <p>
     * * @time 2020/12/3 15:36
     */
    private void uploadFileMinio(String imgPath,String url) {
        new Thread(() -> {
            try {
                Log.e("TAG-路径-----", imgPath);
                File file = new File(imgPath);
                FileInputStream fileInputStream = new FileInputStream(file);
                int available = fileInputStream.available(); //返回与之关联的文件的字节数
                Log.e("字节数---", available + "");
                OkHttpClient httpClient = new OkHttpClient();
                MediaType mediaType = MediaType.parse("image/png");//设置类型
                RequestBody requestBody = RequestBody.create(mediaType, file);//把文件与类型放入请求体
                Request request = new Request.Builder()
                        .url(url)
                        .put(requestBody)
                        .build(); //创建OkHttpClient对象
                Call call = httpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                        Log.e("TAG-失败：", e.toString() + "");
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        assert response.body() != null;
                        String string = response.body().toString();
                        Log.e("minio成功---", string + "");
                        uploadFileTb(imgPath, available + "");
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();


    }

    /**
     * 上传照片到服务器数据库
     *
     * @time 2020/12/2 9:55
     */
    private void uploadFileTb(String imgPathSel, String available) {
        // bucket:   1-病历 2-评论(反馈) 3-头像 4-轮播图 9-聊天图片 ',
        // type:   15-病历 2-评论(反馈) 30-头像 92-聊天图片 ',
        RestProxy.getInstance().uploadFileTb("1", "15", resourceId, BaseApplication.currentUserId, available, "0", new Observer<PicUploadResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(PicUploadResponse picUploadResponse) {
                try {
                    runOnUiThread(() -> {
                        dialog.dismiss();
                        ImageLoaderHelper.getInstance().GlideImageLoader(ChangePhoneActivity.this, picUploadResponse.shareUrl, currentImageView);
                        if (currentImageView == shenfenzheng1) {
                            shenfenzheng1Id = picUploadResponse.resourceId;
                        }
                        if (currentImageView == shenfenzheng2) {
                            shenfenzheng2Id = picUploadResponse.resourceId;
                        }
                        if (currentImageView == shenfenzheng3) {
                            shenfenzheng3Id = picUploadResponse.resourceId;
                        }
                    });

                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(ChangePhoneActivity.this, e);
            }

            @Override
            public void onComplete() {
//                dialog.dismiss();
            }
        });
    }

    /**
     * 创建原图像保存的文件
     */
    protected File createOriImageFile() throws IOException {
        @SuppressLint("SimpleDateFormat") String imgNameOri = "HomePic_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File pictureDirOri = new File(Objects.requireNonNull(getExternalFilesDir(Environment.DIRECTORY_PICTURES)).getAbsolutePath() + "/OriPicture");
        if (!pictureDirOri.exists()) {
            pictureDirOri.mkdirs();
        }
        File image = File.createTempFile(
                imgNameOri,         /* prefix */
                ".jpg",             /* suffix */
                pictureDirOri       /* directory */
        );
        imgPathOri = image.getAbsolutePath();
        return image;
    }

    private SelectPicModeDialog mSelectPicModeDialog = null;


    private void showSelectHeadPicDialog() {
        if (mSelectPicModeDialog == null) {
            // 初始化点击头像弹出的对话框
            mSelectPicModeDialog = SelectPicModeDialog.newInstance();
            mSelectPicModeDialog.setOnItemClickListener(new SelectPicModeDialog.OnItemClickListener() {
                @Override
                public void takePhotoClick() {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File oriPhotoFile = null;
                    try {
                        oriPhotoFile = createOriImageFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                        imgUriOri = Uri.fromFile(oriPhotoFile);
                    } else {
                        assert oriPhotoFile != null;
                        imgUriOri = FileProvider.getUriForFile(ChangePhoneActivity.this, UIConstants.FILE_PROVIDER_URI, oriPhotoFile);
                    }
//                    phoneCamearUri = FileProvider.getUriForFile(PersonInfoActivity.this,"com.joyoung.robot.phone.provider",file);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUriOri);
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    startActivityForResult(intent, REQUEST_OPEN_CAMERA);
                }

                @Override
                public void pickFromAlbumClick() {
                    @SuppressLint("IntentReset") Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(intent, REQUEST_GALLERY);
                }
            });
        }
        mSelectPicModeDialog.show(getSupportFragmentManager(), "SelectPicModeDialog");
    }


    private void getDetail() {
        RestProxy.getInstance().getMyFamilyDetail(id, new BaseObserver<MyFamilyResponse>() {

            @Override
            public void onSuccess(MyFamilyResponse myFamilyResponse) {
                tv_name.setText(myFamilyResponse.name);
                tv_address.setText(myFamilyResponse.addr);
                tv_id_card.setText(myFamilyResponse.idcard);
                tv_area.setText(myFamilyResponse.area);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(ChangePhoneActivity.this, e);

            }

        });
    }


    /**
     * 提交请求接口
     *
     * @time 2020/11/26 9:19
     */
    private void updatePhone() {
        if (UtilString.isEmpty(edt_phone.getText().toString().trim())) {
            ToastUtil.showToast(mContext, "手机号不能为空");
            return;
        }
        if (TextUtils.isEmpty(shenfenzheng1Id) || TextUtils.isEmpty(shenfenzheng2Id) || TextUtils.isEmpty(shenfenzheng3Id)) {
            ToastUtil.showToast(mContext, "请上传身份证照");
            return;
        }
        try {
            RestProxy.getInstance().updatePhone(patientId, AES128.encryptStringAES(edt_phone.getText().toString(), "7t3e506jaa10xbd4"), shenfenzheng1Id + "," + shenfenzheng2Id + "," + shenfenzheng3Id, new BaseObserver<String>() {
                @Override
                public void onError(Throwable e) {
                    ToastUtil.onError(ChangePhoneActivity.this, e);
                }

                @Override
                public void onSuccess(String result) {
                    ToastUtil.showToast(mContext, "提交成功，等待审核");
                    //家族成员
                    Bundle bundleFamily = new Bundle();
                    bundleFamily.putInt(UIConstants.INTO_MyFamilyActivity_FLAG, UIConstants.INTO_MyFamilyActivity_FLAG_1);
                    startActivity(MyFamilyActivity.class, bundleFamily);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("CheckResult")
    private void getPermission() {
        // 缺少权限时, 进入权限配置页面
        if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
            ApplyPermissionDialog applyPermissionDialog = ApplyPermissionDialog.newInstance("3", true);
            applyPermissionDialog.show(getSupportFragmentManager(), "applyPermissionDialog");
            applyPermissionDialog.setmListener(new ApplyPermissionDialog.OnItemClickListener() {

                @RequiresApi(api = Build.VERSION_CODES.O)
                @Override
                public void onConfirm() {
                    RxPermissions permissions = new RxPermissions(ChangePhoneActivity.this);
                    permissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                            .subscribe(granted -> {
                                if (granted) {
                                    //已经打开权限
                                    showSelectHeadPicDialog();
                                } else {
                                    ToastUtil.showToast(mContext, "请同意相册和存储权限，否则功能无法使用");
                                    startNotificationSetting(mContext);
                                }
                            });
                }

                @Override
                public void onCancel() {

                }
            });
        } else {
            showSelectHeadPicDialog();
        }

    }
}
